TodoDataService.createTodo(data, props.token)

.then(response => {

setSubmitted(true);

})

.catch(e => {

console.log(e);

});

}

}

Code Explanation

Analyze Code

if (props.location.state && props.location.state.currentTodo) {

editing = true;

initialTodoTitle = props.location.state.currentTodo.title;

initialTodoMemo = props.location.state.currentTodo.memo;

}

We first check if a state is passed into AddTodo. If you recall in todos-list.js, we pass in a state in the link to edit:

Analyze Code

<Link to={{

pathname: "/todos/" + todo.id,

state: {

currentTodo: todo

}

}}>

<Button variant="outline-info" className="me-2">

Edit

</Button>

</Link>

Thus, in AddTodo, we check if a state is passed in and contains a currentTodo property. If so, set editing to true and

the initialTodoTitle and initialTodoMemo to currentTodo’s title and memo.

Analyze Code

if (editing) {

TodoDataService.updateTodo(

props.location.state.currentTodo.id,

data, props.token)

.then(response => {

setSubmitted(true);

console.log(response.data)

})

.catch(e => {

console.log(e);

})

}

If editing is true, get the existing todo id and call updateTodo in TodoDataService:

Analyze Code

updateTodo(id, data, token){

axios.defaults.headers.common["Authorization"] = "Token " + token;

return axios.put(`http://localhost:8000/api/todos/${id}`, data);

}

The above calls the TodoRetrieveUpdateDestroy view in /api/views.py in the backend similar to how we call

TodoListCreate for adding a todo:

Analyze Code

class TodoRetrieveUpdateDestroy(generics.RetrieveUpdateDestroyAPIView):

serializer_class = TodoSerializer

permission_classes = [permissions.IsAuthenticated]

def get_queryset(self):

user = self.request.user

# user can only update, delete own posts

return Todo.objects.filter(user=user)

Running our App

If you are logged in, you will be able to edit a todo by clicking on the ‘ Edit ’ todo (fig. 6). And if you check your

Admin, the data is updated there.